package com.example.LibrarySystem.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.LibrarySystem.Exception.ServiceException;
import com.example.LibrarySystem.annotation.RoleAnnotation;
import com.example.LibrarySystem.mapper.UserMapper;
import com.example.LibrarySystem.pojo.User;
import com.example.LibrarySystem.response.Result;
import com.example.LibrarySystem.service.UserService;
import com.example.LibrarySystem.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Transactional
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;


    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {

        System.out.println(user);
        Result result = new Result();

        if ("".equals(user.getAccount()) || "".equals(user.getPassword())) {
            result.setMsg("账号或密码为空");
            result.setStatus(-1);
            return result;
        }

        // 对密码进行md5
        String password = DigestUtil.md5Hex(user.getPassword());

        User userNew = userService.login(user.getAccount(), password);


        if (userNew != null) {
            // 判断是否停用
            if(!userNew.isStatus()){
                result.setMsg("该账户已经停用");
                result.setStatus(-1);
                return result;
            }

            // 设置密码为空
            userNew.setPassword("");
            result.put("user", userNew);
            result.put("token", JwtUtil.genToken(userNew.getId().toString(), user.getPassword()));
            result.setMsg("登录成功");
            result.setStatus(200);
        } else {
            result.setMsg("账号或密码错误");
            result.setStatus(-1);
        }
        return result;
    }


    /**
     * 添加一个学生
     *
     * @param user
     * @return
     */
    @PostMapping("/insert")
    @RoleAnnotation(type = "admin")
    public Result insert(@RequestBody User user) {
        Result result = new Result();
        if ("".equals(user.getAccount()) || "".equals(user.getPassword()) || "".equals(user.getName()) || "".equals(user.getSno())) {
            result.setMsg("输入信息为空 请检查");
            result.setStatus(-1);
            return result;
        }
//        user.setRoleName("student");

        // 对密码进行md5
        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        user.setCreationTime(new Date());
        int res = userService.insert(user);
        if (res > 0) {
            result.setMsg("添加成功");
            result.setStatus(200);
        } else {
            result.setMsg("信息输入有误请重试");
            result.setStatus(-1);
        }
        return result;
    }

    /**
     * 退出登录(前端把token清除)
     */
    @GetMapping("/logout")
    public Result logout() {
        return new Result("删除成功", 200);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @RoleAnnotation(type = "admin")
    public Result update(@RequestBody User user) {

        // mybatis-puls 不修改某个字段的话 设置为null就可以了
        if ("".equals(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        }


        int res = userService.update(user);


        Result result = new Result();

        if (res > 0) {
            result.setMsg("修改成功");
            result.setStatus(200);
        } else {
            result.setMsg("修改信息有误 请检查");
            result.setStatus(-1);
        }

        return result;
    }

    /**
     * 查询所有用户
     */
    @GetMapping("/getUserByAll")
    @RoleAnnotation(type = "admin")
    public Result getUserByAll(@RequestParam Map<String, String> data) {
        Result result = new Result();
        IPage<User> userByAll = userService.getUserByAll(data);
        result.put("data", userByAll.getRecords());
        result.put("total", userByAll.getTotal());
        result.setMsg("查询成功");
        result.setStatus(200);
        return result;
    }

    /**
     * 模糊查询学号
     */
    @GetMapping("/getUserLikeSno")
    public Result getUserLikeSno(String sno){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("sno",sno);

        List<User> users = userMapper.selectList(userQueryWrapper);

        Result result = new Result();
        result.setMsg("查询成功");
        result.setStatus(200);
        result.put("data",users);
        return result;
    }

    /**
     * 修改密码
     */
    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody User User,HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("Authorization");
        int id = JwtUtil.verify(token);
        String newPassword = DigestUtil.md5Hex(User.getPassword());
        int res = userMapper.updatePassword(id, newPassword);
        Result result = new Result();
        result.setStatus(200);
        result.setMsg("修改成功");
        return result;

    }
}
